const router = require('koa-router')();
const DB = require('../../module/db.js');
const tools = require('../../module/tools.js');


router.get('/', async (ctx) => {

	let result = await DB.findOne('articlecate', {});
    await ctx.render('admin/articlecate/list', {
    	list: tools.cateToList(result)
    });
});



router.get('/add', async (ctx) => {
	
	// 获取一级分类
	let result = await DB.findOne('articlecate', {pid: '0'});

    await ctx.render('admin/articlecate/add', {
    	cateList: result
    });
});

router.post('/add', async (ctx) => {
	
	let title = ctx.request.body.title;
	let pid = ctx.request.body.pid;
	let keywords = ctx.request.body.keywords;
	let status = ctx.request.body.status;
	let description = ctx.request.body.description;
	
	let addResult = await DB.insertOne('articlecate', {
		title,
		description,
		keywords,
		pid,
		add_time: new Date(),
		status
	});
	
    ctx.redirect(ctx.state.__HOST__ + '/admin/articlecate');
});



router.get('/edit', async (ctx) => {


	let id = ctx.query.id;

	let result = await DB.findOne('articlecate', {
		_id: DB.getObjectID(id)
	});
	
	// 获取一级分类
	let cateResult = await DB.findOne('articlecate', {pid: '0'});
	
    await ctx.render('admin/articlecate/edit', {
    	list: result[0],
    	cateList: cateResult
    });
});

router.post('/edit', async (ctx) => {
	
	let id = ctx.request.body.id;
	let title = ctx.request.body.title;
	let pid = ctx.request.body.pid;
	let keywords = ctx.request.body.keywords;
	let status = ctx.request.body.status;
	let description = ctx.request.body.description;
	
	let editResult = await DB.updateOne('articlecate', {
		_id: DB.getObjectID(id)
	}, {
		title,
		description,
		keywords,
		pid,
		status
	});
	
	ctx.redirect(ctx.state.__HOST__ + '/admin/articlecate');
});



router.get('/delete', async (ctx) => {

    ctx.body = '删除用户';
});

module.exports = router.routes();